from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
import random
import logging
from django_redis import get_redis_connection
from rest_framework.response import Response

from . import constants
from meiduo.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.

# 创建日志输出器对象
logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):

        # 创建连接对象
        redis_conn = get_redis_connection('verify_code')

        # 来发送验证码前先去redis去一下短信标记
        flag = redis_conn.get('sms_flag_%s' % mobile)

        if flag:
            return Response({'message': "频繁发送短信"}, status=status.HTTP_404_NOT_FOUND)

        # 生成验证码
        sms_code = "%06d" % (random.randint(0, 999999))
        logger.info(sms_code)
        # print(sms_code)

        # 创建redis管道
        pl = redis_conn.pipeline()

        # 存储一个已经发送过短信的标志
        # redis_conn.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 把验证码存储到redis
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 使用容联云通讯发送短信验证码

        # 执行管道  才会一次全部执行
        pl.execute()
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], 1)
        send_sms_code.delay(mobile, sms_code)
        # 响应
        return Response({"message": 'OK'})


